<?php

class SEOPosFinder
{
	function __construct($link, $text, $maxPos=500)
	{
		$this->link = strtolower( self::getSiteName($link) );
		$this->text = urlencode($text);
		$this->maxPos = $maxPos;
	}
	
	static public function getSiteName($url)
	{
		$matches = array();
		if (!preg_match('|(http://)?(www.)?([^/]*)|', $url, $matches) || empty($matches[3])) {
			throw new Exception("Invalid URL: $url");
		}
		return $matches[3];
	}
	
	public function foundPos()
	{
		return $this->posCount;
	}
	
	public function foundLink()
	{
		return $this->findLink;
	}
	
	protected function processLink($link)
	{
		++$this->posCount;
		
		if ($this->link == strtolower( self::getSiteName($link) ))
		{
			$this->findLink = $link;
			return true;
		}
		if ($this->posCount >= $this->maxPos)		//max pos exceeded
		{
			$this->posCount = 0;
			return true;
		}
		return false;
	}
	
	protected $link = '';
	protected $findLink = '';
	protected $text = '';
	protected $maxPos = 0;
	private $posCount = 0;
}




class YandexPosFinder extends SEOPosFinder
{
	const MAX_PAGES = 100;
	
	function __construct($link, $text, $region=0)
	{
		parent::__construct($link, $text);
		$this->region = $region;
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, 		'Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 	1);
		//curl_setopt($ch, CURLOPT_HEADER,			1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,	1);
		$fCookies = 'curl_cookies';
		curl_setopt($ch, CURLOPT_COOKIEJAR,			$fCookies);
		curl_setopt($ch, CURLOPT_COOKIEFILE, 		$fCookies); 

		$pgNum = 0;
		while ( !$this->findOnPage($ch, $pgNum++) && $pgNum<self::MAX_PAGES ) 
		{
//			curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
			sleep(2);
		}
		
		curl_close($ch);
	}
	
	private function findOnPage($ch, $pgNum)
	{
		$pageUrl = 'http://yandex.ru/yandsearch?lr=213&text='.$this->text;
		if ($pgNum > 0) {
			$pageUrl .= "&p=$pgNum";
		}
		
		$pageUrl = 'http://yandex.ru/yandsearch?text=test&lr=213';
		
		curl_setopt($ch, CURLOPT_URL, $pageUrl);
		$s = curl_exec($ch);
		if (!$s)
		{
			//throw new Exception('curl_exec returned FALSE, error: ['.curl_errno($ch).']'.curl_error($ch));
			//print_r(curl_getinfo($ch));  [http_code] => 302  The temporary URI SHOULD be given by the Location field in the response.
		}
		echo $s;
		exit;

		
		$doc = new DOMDocument;
		$doc->loadHTML($s);
		
		$linkNodes = $doc->getElementsByTagName('a');
		
		foreach ($linkNodes as $node) 
		{
			$className = $node->attributes->getNamedItem('class');
			if ($className && $className->nodeValue == 'b-serp-item__title-link')
			{
				if ($node->attributes->getNamedItem('tabindex'))
				{
					if ($this->processLink( $node->attributes->getNamedItem('href')->nodeValue )) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	private $region = 0;
}


?>